﻿using System.Text;
using System.IO;
using BotDetector.Core.Model;
using BotDetector.Core.Search;
using BotDetector.Core.Detector;

namespace BotDetector.ValidationTest
{
    public class Validator
    {
        private const string inputFile = "in.txt";
        private const string outputFile = "out.txt";

        private StreamReader reader = new StreamReader(inputFile);
        private StreamWriter writer = new StreamWriter(outputFile);
        private GoogleBingAggregator aggregator = new GoogleBingAggregator();
        private ResultItemList results;
        private ResultItemList results2;
        private bool isBotGoogle;
        private bool isBotBing;
        private bool isBotBoth;

        public void Validate()
        {
            string line;            
            writer.AutoFlush = true;
            while ((line = reader.ReadLine()) != null)
            {
                string[] parts;
                parts = line.Split(new char[] { ',' }, 2);
                SearchForResults(parts[1]);
                AnalyzeResults();
                writer.WriteLine(BuildOutString(parts[1], parts[0]));
            }
        }


        public void SearchForResults(string phrase)
        {
            ISearch searchEngine = new GoogleSearch();
            results = searchEngine.Search(phrase);
            searchEngine = new BingSearch();
            results2 = searchEngine.Search(phrase);
        }

        public void AnalyzeResults()
        {
            IBotDetector detector = new BotDetector.Core.Detector.BotDetector();
            isBotGoogle = detector.IsBot(results);
            isBotBing = detector.IsBot(results2);
            results = aggregator.AggregateGoogleAndBingResultsItemLists(results, results2);
            isBotBoth = detector.IsBot(results);
        }

        public string BuildOutString(string phrase,string isBot)
        {
            StringBuilder builder = new StringBuilder(isBot.ToString());
            builder.Append(",");
            builder.Append(isBotBing.ToString());
            builder.Append(",");
            builder.Append(isBotGoogle.ToString());
            builder.Append(",");
            builder.Append(isBotBoth.ToString());
            builder.Append(",");
            builder.Append(phrase);
            return builder.ToString();
        }
    }
}
